package com.hzcx.app.simplechat.view;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.AttributeSet;
import android.widget.ImageView;

import androidx.appcompat.widget.AppCompatEditText;

import com.hzcx.app.simplechat.R;

/**
 *  统一的密码输入框
 */
public class MainPwdEditText extends AppCompatEditText {

    private Context context;
    private boolean isPwdHide=true;

    public MainPwdEditText(Context context) {
        super(context);
        this.context=context;
        init();
    }

    public MainPwdEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context=context;
        init();
    }

    public MainPwdEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context=context;
        init();
    }

    /**
     *  初始化，监听密码显示或隐藏
     */
    private void init(){
        setBackgroundColor(context.getResources().getColor(R.color.color_00000000));
    }

    /**
     *  设置显示或者隐藏密码的imageview
     * @param ivPwdState
     */
    public void setIvPwdState(ImageView ivPwdState){
        ivPwdState.setVisibility(INVISIBLE);
        addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if(getText().toString().length()>0){
                    ivPwdState.setVisibility(VISIBLE);
                }else {
                    ivPwdState.setVisibility(INVISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        // 设置密码显示或隐藏
        ivPwdState.setOnClickListener(view -> {
            if(isPwdHide){
                ivPwdState.setImageResource(R.mipmap.ic_icon_pwd_show);
                setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            }else {
                ivPwdState.setImageResource(R.mipmap.ic_icon_pwd_hide);
                setTransformationMethod(PasswordTransformationMethod.getInstance());
            }
            isPwdHide=!isPwdHide;
        });
    }
}
